package newui.page;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.TrainActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.MainActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.customview.BannerOnClickListener;
import com.shwread.android.ui.customview.QYViewPager;
import com.shwread.android.ui.customview.ViewPagerAdapter;
import com.shwread.android.ui.dialog.GuideDialog;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.page.AbstractUIPage;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.util.NetUtil;
import com.tgx.tina.android.ipc.framework.IUIPage;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import base.tina.core.task.infc.ITaskResult;
import logic.bean.BannerInfo;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import newui.activity.BookListWebActivity;
import newui.activity.MomentActivity;
import newui.view.MomentContentView;
import newui.view.MyScrollView;
import newui.view.PullToRefreshScrollView;

/**
 * Created by lex on 2017/7/8.
 */

public class SharePage extends
        AbstractUIPage<MainActivity> implements View.OnClickListener,MyScrollView.OnScrollListener
{
    public static SharePage instance;
    public static SharePage getInstance(MainActivity t) {
        if (null == instance) {
            instance = new SharePage(t);
        } else {
            instance.setActivity(t);
        }
        return instance;
    }
    public SharePage(MainActivity t) {
        super(t);
    }

    private TextView tvTitle;
    private ImageView 	ivPersion;

    private View loadingView, freshView;
    private ImageView loadingImg;
    private AnimationDrawable animationDrawable;

    private PullToRefreshScrollView contentView;

    private LinearLayout ll_interaction_contentview;
    public MomentContentView contentItemView;
    private int pagetype;// 页面类型 0普通用户   1经理   2 为客户


    private final int TEACHER = 1;
    private final int STUDENT = 2;
    private final int HELP = 3;

    /**
     * 没有网络0 ，没有主题1
     */
    private int net_theme = 3;

    private LinearLayout nonet_theme_ll;
    private Button setnet;
    private ImageView no_nettheme_img;
    private TextView no_nettheme_tv;
    public static int width, height;

    private GuideDialog dialog;
    private boolean showHelp;
    private QyreaderPerferencesUtil util;

    private LinearLayout llTeacherShare,llShareHelp,llStudentShare;

    private LinearLayout llHoveringView1,llHoveringView2_1,llHoveringView2_2,llTopView;
    private QYViewPager vpPager;
    private ViewGroup vgPoints;
    private HashMap<Integer, View> views;
    private ViewPagerAdapter pagerAdapter;
    private List<BannerInfo> banners;
    private LinearLayout llVp;

    private void initGuide() {
        util = QyreaderPerferencesUtil.getInstance(bActivity, DefaultConsts.FIRST_TAG);
        dialog = new GuideDialog(bActivity, R.layout.enterprise_page_firstin);
    }

    Runnable action = new Runnable() {
        @Override
        public void run() {
            int currentItem = vpPager.getCurrentItem();
            currentItem++;
            if (currentItem >= pagerAdapter.getCount()) {
                currentItem = 0;
            }
            vpPager.setCurrentItem(currentItem);
        }
    };

    private void showGuide() {
        if (util == null || dialog == null) {
            initGuide();
        }
        showHelp = util.getShowEnterpriseHelp();
        if (showHelp) {
            if (null != dialog && !dialog.isShowing()) {
                dialog.show();
            }
            util.setShowEnterpriseHelp(false);
        }
    }
    @Override
    public <E extends Activity> View createView(E arg0, int arg1) {
        if (null != curMyView) return curMyView;
        curMyView = bActivity.getLayoutInflater().inflate(R.layout.page_share, null);
        WindowManager manage = bActivity.getWindowManager();
        width = manage.getDefaultDisplay().getWidth();
        height = manage.getDefaultDisplay().getHeight();
        initView();
        initGuide();
        setPageInfo();
        return curMyView;
    }

    void initView() {
        llHoveringView1 = (LinearLayout) curMyView.findViewById(R.id.llHoveringView1);
        llHoveringView2_1 = (LinearLayout) curMyView.findViewById(R.id.llHoveringView2_1);
        llHoveringView2_2 = (LinearLayout) curMyView.findViewById(R.id.llHoveringView2_2);
        llTopView = (LinearLayout) curMyView.findViewById(R.id.llTopView);

        llTeacherShare = (LinearLayout) curMyView.findViewById(R.id.llTeacherShare);
        llShareHelp = (LinearLayout) curMyView.findViewById(R.id.llShareHelp);
        llStudentShare = (LinearLayout) curMyView.findViewById(R.id.llStudentShare);
        llTeacherShare.setOnClickListener(this);
        llShareHelp.setOnClickListener(this);
        llStudentShare.setOnClickListener(this);

        tvTitle = (TextView) curMyView.findViewById(R.id.common_header_name);
        tvTitle.setText(bActivity.getResources().getString(R.string.main_tab_str4));
        ivPersion = (ImageView) curMyView.findViewById(R.id.common_header_persion);
        ivPersion.setVisibility(View.VISIBLE);
        ivPersion.setOnClickListener(this);

        loadingView = curMyView.findViewById(R.id.common_loading_layout);
        loadingImg = (ImageView) curMyView.findViewById(R.id.common_loading__img);
        freshView =  curMyView.findViewById(R.id.refreshView);

        contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.iteraction_center_view);

        ll_interaction_contentview = (LinearLayout) curMyView.findViewById(R.id.ll_interaction_contentview);
        no_nettheme_img = (ImageView) curMyView.findViewById(R.id.new_interaction_no_theme_img);
        // 设置网络按钮
        setnet = (Button) curMyView.findViewById(R.id.new_interaction_no_theme_btn_setting);
        // 没网络或没主题的提示文字
        no_nettheme_tv = (TextView) curMyView.findViewById(R.id.new_interaction_no_theme_tv_text);
        contentView = (PullToRefreshScrollView) curMyView.findViewById(R.id.iteraction_center_view);
        nonet_theme_ll = (LinearLayout) curMyView.findViewById(R.id.new_no_theme_ll);

        banners = new ArrayList<>();
        views = new HashMap<>();
        vpPager = (QYViewPager) curMyView.findViewById(R.id.share_head_pager);
        vgPoints = (ViewGroup) curMyView.findViewById(R.id.share_head_points);// banner下面的点

        llVp = (LinearLayout) curMyView.findViewById(R.id.llVp);
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) llVp.getLayoutParams();
        lp.height = DefaultConsts.BANNER_DEFAULT_HIGHT;
        lp.width = DefaultConsts.BANNER_DEFAULT_WIDTH;
        llVp.setLayoutParams(lp);

        vpPager.setOnPageChangeListener(new PagerChangeListener());
        pagerAdapter = new ViewPagerAdapter(bActivity, views, new BannerClick());
        vpPager.setAdapter(pagerAdapter);

        if (net_theme == 1) {// 没主题
            contentView.setVisibility(View.GONE);
            nonet_theme_ll.setVisibility(View.VISIBLE);
            setnet.setVisibility(View.GONE);
            no_nettheme_tv.setText("没有主题哦，立即发布！");
            no_nettheme_img.setBackgroundResource(R.drawable.new_i_no_theme_icon);
        } else if (net_theme == 0) {// 没网络
            contentView.setVisibility(View.GONE);
            nonet_theme_ll.setVisibility(View.VISIBLE);
        }

        PullToRefreshUtil.initLabel(context, contentView);

        // 增加内容项视图
        if (Const.UserRole.equals("0")) {
            pagetype = 0;// 普通用户
        } else if (Const.UserRole.equals("1")) {
            pagetype = 1;//客户经理
        } else if (Const.UserRole.equals("2")) {
            pagetype = 2;//客户
        }
        contentItemView = new MomentContentView(context);
        contentItemView.setFromType(pagetype);
        contentItemView.setBaseActivity(bActivity);
        contentItemView.setInteractionContentViewListener(new MomentContentView.InteractionContentViewListener() {
            @Override
            public void OnLoadDataCompleted(int flag) {
                if (flag == 0) {
                    // 首次装载
                    contentView.onRefreshComplete();
                } else if (flag == 1) { // 刷新装载
                    contentView.onRefreshComplete();
                } else if (flag == 2) {// 装载更多
                    contentView.onRefreshComplete();
                }
            }
        });

        contentView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<MyScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<MyScrollView> refreshView) {
                if (contentView.isHeaderShown()) { // 下拉刷新
                    refresh();
                }
//                else if (contentView.isFooterShown()) { // 上拉加载
//                    loadMore();
//                }
            }
        });

        clearPage();


        //悬停效果
        contentView.getRefreshableView().setOnScrollListener(this);
        TrainActionHelp.qryBannerListByPosition(bActivity, 8, new QryBannerListByPositionHandler());
    }

    private void clearPage() {
        ll_interaction_contentview.addView(contentItemView);
    }

    /**
     * 下拉刷新
     */
    private void refresh() {
        // TODO
        if (NetUtil.isNetworkConnected(context)) {
            contentItemView.getInteractionData(1);
            //			rlayNoNetTopTip.setVisibility(View.GONE);
        } else {
            //			rlayNoNetTopTip.setVisibility(View.VISIBLE);
            contentView.onRefreshComplete();
            new NoNetDialog(context).show();
        }
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if (!NetUtil.isNetworkConnected(context)) {

            //			rlayNoNetTopTip.setVisibility(View.VISIBLE);
        } else {
            //			rlayNoNetTopTip.setVisibility(View.GONE);

            if (contentItemView.getDataSize() == 0) {
                PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
            } else {
                if (contentItemView.getHasMore()) {
                    // 加载下一页
                    contentItemView.getNextPage();
                    return;
                } else if (contentItemView.isGotMaxSize()) {
                    // 已经达到了最大条数，
                    //				PullToRefreshUtil.setLoadLabel(contentView, "已经达到了最大条数");
                    PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
                } else {
                    // 没有更多了， 所以不再加载下一页
                    PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
                }
            }
        }
        contentView.onRefreshComplete();
    }

    private void setPageInfo() {
        if (Const.UserRole.equals("2")) {
            pagetype = 2;
        } else if (Const.UserRole.equals("1")) {
            pagetype = 1;
        } else if (Const.UserRole.equals("0")) {
            pagetype = 0;
        }
    }

    @Override
    public int enter(IUIPage<?> arg0) {
        if (NetworkUtil.isNetAvailable(bActivity)) {
            setPageInfo();
            // clearPage();
            contentItemView.setFromType(pagetype);
            contentItemView.updateSwitchView(0);// 加载动画
            contentItemView.getInteractionData(0);// 初始装载
            contentItemView.getInteractionData(1);
            //			rlayNoNetTopTip.setVisibility(View.GONE);
        } else {
            //			new NoNetDialog(bActivity).show();
            //			rlayNoNetTopTip.setVisibility(View.VISIBLE);
        }
        return 0;
    }

    @Override
    public int leave(IUIPage<?> arg0) {
        return 0;
    }

    @Override
    public void notifyView(int arg0, Bundle arg1) {
        switch (arg0) {
            case DefaultConsts.PAGE_ONRESUME_CODE:
                // contentItemView.getInteractionData(1);
//                qryUnReadTotal();
                //				long lastQryTime = QyreaderPerferencesUtil.getInstance(bActivity, Const.phone_number).getLastQryTime();
                //				if (pagetype == 1) new QryUnReadActivityAction(bActivity, lastQryTime, new GetUnReadActivity()).start();
                break;
            case DefaultConsts.MESSAGE_UNREAD_CHANGE_CODE:
                boolean res = arg1.getBoolean("result");
                //				ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
                break;
            case BaseBusinessActivity.COMMENTS_REQUEST_CODE:
                //互动中心评论发送成功
                contentItemView.updateComment(arg1.getInt("position"), arg1.getInt("count"));
                break;
            case DefaultConsts.START_PUBLISH_THEME_ACTIVITY:
                contentItemView.getInteractionData(1);
                break;
        }
    }

    @Override
    public void setStatus(int arg0) {

    }

    @Override
    public View updateView(int arg0, ITaskResult arg1) {
        return null;
    }

    public static void destroy() {
        if (instance != null) {
            instance.dispose();
            instance = null;
        }
    }

    @Override
    public void dispose() {
        super.dispose();
    }

    /**
     * @param flag 0:加载中，1：加载完成，-1：加载失败
     */
    private void updateLoadingView(int flag) {
        switch (flag) {
            case -1:
                loadingView.setVisibility(View.VISIBLE);
                freshView.setVisibility(View.GONE);
                if (animationDrawable != null && animationDrawable.isRunning()) {
                    animationDrawable.stop();
                }
                loadingImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                loadingView.setVisibility(View.VISIBLE);
                freshView.setVisibility(View.GONE);
                loadingImg.setBackgroundResource(R.drawable.home_progress);
                animationDrawable = (AnimationDrawable) loadingImg.getBackground();
                animationDrawable.start();
                break;
            case 1:
                loadingView.setVisibility(View.GONE);
                freshView.setVisibility(View.VISIBLE);
                break;
        }
    }

    private int clickCount;
    private long preClickTime;
    /**
     * 双击有效时间500毫秒
     */
    private final int defalultValue = 500;

    /**
     * 标题栏双击，回到顶部
     */
    private void titleDoubleClick() {
        if (clickCount == 0) {
            preClickTime = System.currentTimeMillis();
            clickCount++;
        } else if (clickCount == 1) {
            if ((System.currentTimeMillis() - preClickTime) < defalultValue) {
                gotoTop();
            }
            clickCount = 0;
            preClickTime = 0;
        } else {
            clickCount = 0;
            preClickTime = 0;
        }
    }

    /**
     * 回到顶部
     */
    private void gotoTop() {
        contentItemView.post(new Runnable() {
            @Override
            public void run() {
                contentView.getRefreshableView().scrollTo(0, 0);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.common_header_persion:
                bActivity.goPersonalActivity();
                break;
            case R.id.llTeacherShare:
                shareIntent(TEACHER);
                break;
            case R.id.llShareHelp:
                shareIntent(HELP);
                break;
            case R.id.llStudentShare:
                shareIntent(STUDENT);
                break;
        }
    }

    public void shareIntent(int releaseType){
        Intent intent = new Intent(bActivity, MomentActivity.class);
        intent.putExtra("releaseType",releaseType);
        bActivity.startActivity(intent);
    }

    @Override
    public void onScroll(int scrollY) {
        int topH = llTopView.getBottom();
        if (scrollY >= topH) {
            if (llHoveringView2_2.getParent() != llHoveringView1) {
                llHoveringView2_1.removeView(llHoveringView2_2);
                llHoveringView1.addView(llHoveringView2_2);
            }
        } else {
            if (llHoveringView2_2.getParent() != llHoveringView2_1) {
                llHoveringView1.removeView(llHoveringView2_2);
                llHoveringView2_1.addView(llHoveringView2_2);
            }
        }
    }


    /**
     * Banner点击事件
     */
    private class BannerClick implements BannerOnClickListener {
        @Override
        public void click(BannerInfo info) {
            clickBanner(info);
        }
    }

    /**
     * Banner的滚动事件
     */
    private class PagerChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrollStateChanged(int state) {
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageSelected(int i) {
            int pageIndex = i;
            if (i == 0) {
                // 当视图在第一个时，将页面号设置为图片的最后一张。
                pageIndex = banners.size() - 2;
            } else if (i == banners.size() - 1) {
                // 当视图在最后一个是,将页面号设置为图片的第一张。
                pageIndex = 1;
            }
            if (i != pageIndex) {
                vpPager.setCurrentItem(pageIndex, false);
            }
            setViewPoint();
            startScroll();
        }
    }


    private void initBannerView() {
        if (banners.size() == 0) {
            return;
        }
        vgPoints.removeAllViews();
        for (int i = 0; i < banners.size() - 2; i++) {
            View view = bActivity.getLayoutInflater().inflate(R.layout.banner_grid_item, null);
            vgPoints.addView(view);
        }
        vpPager.setCurrentItem(1);
        setViewPoint();
        // pagerAdapter.setData(banners);
        pagerAdapter.notifyDataSetChanged();
        startScroll();
    }

    private void setViewPoint() {
        for (int i = 0; i < vgPoints.getChildCount(); i++) {
            View view = vgPoints.getChildAt(i);
            ImageView img = (ImageView) view.findViewById(R.id.banner_grid_item_image);

            if (i == vpPager.getCurrentItem() - 1) {
                img.setBackgroundResource(R.drawable.banner_grid_cur);
            } else {
                img.setBackgroundResource(R.drawable.banner_grid);
            }
        }
    }

    private void startScroll() {
        if (banners.size() <= 1) {
            return;
        }
        vpPager.removeCallbacks(action);
        vpPager.postDelayed(action, DefaultConsts.BANNER_CHANGE_TIME);
    }

    void clickBanner(BannerInfo info) {
        switch (info.getType()) {
            case BannerInfo.TYPE_BANNER:
                break;
            case BannerInfo.TYPE_BOOKS:
                break;
            case BannerInfo.TYPE_BOOKSURL:
                bActivity.goBookDetailActivity(info.getBooks());
                break;
            case BannerInfo.TYPE_URL:
            case BannerInfo.TYPE_INFORMATION:
//                bActivity.goWebViewActivity(info);
                Intent webIntent = new Intent(bActivity, BookListWebActivity.class);
                webIntent.putExtra(DefaultConsts.title_s, info.getBannerName());
                webIntent.putExtra(DefaultConsts.req_url_s, info.getContent());
                webIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                bActivity.startActivity(webIntent);
                break;
        }
    }


    public class QryBannerListByPositionHandler extends
            ObjectHttpResponseHandler<List<BannerInfo>> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//            updateLoadingView(-1);
//            isLastSuccess = false;

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, List<BannerInfo> object, String responseString) {
            banners.clear();
            if (object.size() <= 1) {
                banners = object;
            } else {
                banners.add(object.get(object.size() - 1));
                banners.addAll(object);
                banners.add(object.get(0));
            }
            System.out.println("企业专区banner obj:" + banners.toString());
            if (banners.size() > 0) {
                pagerAdapter.setData(banners);
                initBannerView();
            }
//            updateLoadingView(1);
//            gotoTop();
        }

        @Override
        public Type getType() {
            return new TypeToken<List<BannerInfo>>() {
            }.getType();
        }
    }
}